package com.ximu.user.service.impl;

import com.ximu.common_utlis.jwt.JwtUtil;


import com.ximu.redis.RedisUtil;
import com.ximu.user.entity.LoginUser;
import com.ximu.user.entity.User;
import com.ximu.user.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @projectName: java
 * @package: com.ximu.service_ucenter.service.impl
 * @className: LoginServiceImpl
 * @author: ximu
 * @description: null
 * @date: 2022/5/14 17:57
 * @version: 1.0
 */
@Service
public class LoginServiceImpl implements LoginService {

    //认证管理
    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public String login(User user) {
        //AuthenticationManager authenticate进行认证
        //这里只能传Authentication对象，得把用户封装一下
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        Authentication rsAuthentication = authenticationManager.authenticate(authenticationToken);
        //认证失败
        if (Objects.isNull(rsAuthentication)){
            throw new RuntimeException("登录失败");
        }
        //认证成功，id生成jwt
        LoginUser users = (LoginUser)rsAuthentication.getPrincipal();
        String userId = users.getUser().getUserId().toString();
        String jwt = JwtUtil.createJWT(userId);

        //存入redis
        redisUtil.setCacheObject("hongsai:login"+userId,user);

        return jwt;

    }



    @Override
    public void logout(int id) {
        //获取用户id
//        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
//        LoginUser loginUser = (LoginUser)authentication.getPrincipal();
//        long userId = loginUser.getUser().getUserId();

        //删除redis的存值
        redisUtil.deleteObject("hongsai:login"+id);

    }
}
